using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace DesktopHelper.Views
{
    public partial class PinnedImageWindow : Window
    {
        private bool _isDragging;
        private Point _dragStartPoint;
        private bool _isResizing;
        private Point _resizeStartPoint;
        private Size _originalSize;

        public int PinnedImageId { get; set; }
        public string ImagePath { get; private set; } = string.Empty;

        // 事件
        public event EventHandler? PositionChanged;
        public event EventHandler? OpacityChanged;

        public PinnedImageWindow(string imagePath)
        {
            InitializeComponent();
            ImagePath = imagePath;
            LoadImage();
            
            // 设置初始位置
            Left = 100;
            Top = 100;
            
            // 记录原始大小
            Loaded += (s, e) => 
            {
                _originalSize = new Size(ActualWidth, ActualHeight);
                // 设置焦点以接收键盘事件
                Focus();
            };
        }

        private void LoadImage()
        {
            try
            {
                if (File.Exists(ImagePath))
                {
                    var bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(ImagePath);
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    bitmap.Freeze();

                    MainImage.Source = bitmap;
                    
                    // 设置窗口大小以适应图片，但限制最大尺寸
                    var maxWidth = SystemParameters.WorkArea.Width * 0.8;
                    var maxHeight = SystemParameters.WorkArea.Height * 0.8;
                    
                    var imageWidth = bitmap.PixelWidth;
                    var imageHeight = bitmap.PixelHeight;
                    
                    if (imageWidth > maxWidth || imageHeight > maxHeight)
                    {
                        var ratio = Math.Min(maxWidth / imageWidth, maxHeight / imageHeight);
                        Width = imageWidth * ratio;
                        Height = imageHeight * ratio;
                    }
                    else
                    {
                        Width = imageWidth;
                        Height = imageHeight;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载图片失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                // 双击查看原图
                ViewOriginalImage();
            }
            else
            {
                // 开始拖拽
                _isDragging = true;
                _dragStartPoint = e.GetPosition(this);
                MainImage.CaptureMouse();
            }
        }

        private void Image_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDragging && e.LeftButton == MouseButtonState.Pressed)
            {
                var currentPosition = e.GetPosition(this);
                var deltaX = currentPosition.X - _dragStartPoint.X;
                var deltaY = currentPosition.Y - _dragStartPoint.Y;

                Left += deltaX;
                Top += deltaY;
            }
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_isDragging)
            {
                _isDragging = false;
                MainImage.ReleaseMouseCapture();
                PositionChanged?.Invoke(this, EventArgs.Empty);
            }
        }

        private void Image_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 右键菜单由 ContextMenu 处理
        }

        private void Image_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            // 滚轮调整透明度
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                var delta = e.Delta > 0 ? 0.1 : -0.1;
                Opacity = Math.Max(0.1, Math.Min(1.0, Opacity + delta));
                OpacityChanged?.Invoke(this, EventArgs.Empty);
                e.Handled = true;
            }
        }

        private void ResizeGrip_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _isResizing = true;
            _resizeStartPoint = e.GetPosition(this);
            ResizeGrip.CaptureMouse();
        }

        private void ResizeGrip_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isResizing && e.LeftButton == MouseButtonState.Pressed)
            {
                var currentPosition = e.GetPosition(this);
                var deltaX = currentPosition.X - _resizeStartPoint.X;
                var deltaY = currentPosition.Y - _resizeStartPoint.Y;

                var newWidth = Math.Max(MinWidth, Width + deltaX);
                var newHeight = Math.Max(MinHeight, Height + deltaY);
                
                // 保持宽高比
                if (MainImage.Source is BitmapSource bitmap)
                {
                    var aspectRatio = (double)bitmap.PixelWidth / bitmap.PixelHeight;
                    var widthBasedHeight = newWidth / aspectRatio;
                    var heightBasedWidth = newHeight * aspectRatio;
                    
                    if (Math.Abs(deltaX) > Math.Abs(deltaY))
                    {
                        Width = newWidth;
                        Height = widthBasedHeight;
                    }
                    else
                    {
                        Width = heightBasedWidth;
                        Height = newHeight;
                    }
                }
                else
                {
                    Width = newWidth;
                    Height = newHeight;
                }

                _resizeStartPoint = currentPosition;
            }
        }

        private void ResizeGrip_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_isResizing)
            {
                _isResizing = false;
                ResizeGrip.ReleaseMouseCapture();
            }
        }

        private void Border_Drop(object sender, DragEventArgs e)
        {
            // 处理拖拽文件
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length > 0)
                {
                    var filePath = files[0];
                    var extension = Path.GetExtension(filePath).ToLower();
                    
                    if (extension == ".png" || extension == ".jpg" || extension == ".jpeg" || 
                        extension == ".bmp" || extension == ".gif")
                    {
                        ImagePath = filePath;
                        LoadImage();
                    }
                }
            }
        }

        private void SaveImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new SaveFileDialog
                {
                    Filter = "PNG图片|*.png|JPEG图片|*.jpg|所有文件|*.*",
                    DefaultExt = ".png",
                    FileName = $"PinnedImage_{DateTime.Now:yyyyMMddHHmmss}"
                };

                if (dialog.ShowDialog() == true)
                {
                    File.Copy(ImagePath, dialog.FileName, true);
                    MessageBox.Show("图片已保存", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CopyImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MainImage.Source is BitmapSource bitmap)
                {
                    Clipboard.SetImage(bitmap);
                    MessageBox.Show("图片已复制到剪贴板", "成功", 
                                   MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SetOpacity_Click(object sender, RoutedEventArgs e)
        {
            if (sender is System.Windows.Controls.MenuItem menuItem && 
                menuItem.Tag is string opacityStr &&
                double.TryParse(opacityStr, out var opacity))
            {
                Opacity = opacity;
                OpacityChanged?.Invoke(this, EventArgs.Empty);
            }
        }

        private void SetSize_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is System.Windows.Controls.MenuItem menuItem && menuItem.Tag is string sizeStr)
                {
                    if (sizeStr == "original")
                    {
                        if (MainImage.Source is BitmapSource bitmap)
                        {
                            Width = bitmap.PixelWidth;
                            Height = bitmap.PixelHeight;
                        }
                    }
                    else if (double.TryParse(sizeStr, out var scale))
                    {
                        Width = _originalSize.Width * scale;
                        Height = _originalSize.Height * scale;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"调整大小失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ToggleTopmost_Click(object sender, RoutedEventArgs e)
        {
            Topmost = !Topmost;
        }

        private void HideWindow_Click(object sender, RoutedEventArgs e)
        {
            Hide();
        }

        private void CloseWindow_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void ViewOriginalImage()
        {
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = ImagePath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开图片失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        protected override void OnLocationChanged(EventArgs e)
        {
            base.OnLocationChanged(e);
            PositionChanged?.Invoke(this, EventArgs.Empty);
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            // ESC键关闭钉图窗口
            if (e.Key == Key.Escape)
            {
                Close();
                e.Handled = true;
            }
        }
    }
}